<template>
  <div class="app-container">
    <el-table v-loading="loading" :data="matchesList" border style="width: 100%" @expand-change="handleExpand">
      <el-table-column type="expand">
        <template slot-scope="scope">
          <template v-if="scope.row.videos">
            <div class="videos-container">
              <div v-for="(video, index) in parseVideos(scope.row.videos)" :key="index" class="video-item">
                <div class="video-name">{{ video.name }}</div>
                <video :src="baseUrl + video.url" controls class="video-player">您的浏览器不支持视频标签</video>
              </div>
            </div>
          </template>
          <el-empty v-else description="暂无视频"></el-empty>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" width="160">
        <template slot-scope="scope">
          {{ scope.row.startTime }}
        </template>
      </el-table-column>
      <el-table-column label="比赛名称" prop="matchName" align="center" />
      <el-table-column label="比赛类型" prop="matchType" align="center" width="100" />
      <el-table-column label="队伍A" align="center" width="200">
        <template slot-scope="scope">
          <div class="team-info">
            <img :src="baseUrl + scope.row.teamAImg" class="team-logo" />
            <span>{{ scope.row.teamAname }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="比分" prop="res" align="center" width="100" />
      <el-table-column label="队伍B" align="center" width="200">
        <template slot-scope="scope">
          <div class="team-info">
            <img :src="baseUrl + scope.row.teamBImg" class="team-logo" />
            <span>{{ scope.row.teamBname }}</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="280">
        <template slot-scope="scope">
          <el-button v-if="!scope.row.editing" type="primary" size="mini"
            @click="startEditing(scope.row)">编辑比分</el-button>
          <div v-else>
            <el-input v-model="scope.row.res" size="mini" style="width: 80px; margin-right: 5px" />
            <el-button type="success" size="mini" circle icon="el-icon-check" @click="handleScoreEdit(scope.row)" />
            <el-button type="danger" size="mini" circle icon="el-icon-close" @click="cancelEdit(scope.row)" />
          </div>
          <el-button size="mini" type="primary" @click="handleAddVideo(scope.row)">新增视频</el-button>
          <el-button size="mini" type="primary" @click="handleAddjl(scope.row)">比赛记录</el-button>
          <!-- 删除 -->
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="query.pageNum" :limit.sync="query.pageSize"
      @pagination="getMatchesList" />

    <!-- 新增视频对话框 -->
    <el-dialog title="新增视频" :visible.sync="dialogVisible" width="500px">
      <el-form :model="videoForm" :rules="rules" ref="videoForm" label-width="80px">
        <el-form-item label="视频名称" prop="name">
          <el-input v-model="videoForm.name" placeholder="请输入视频名称"></el-input>
        </el-form-item>
        <el-form-item label="视频链接" prop="url">
          <FileUpload v-model="videoForm.url" :fileType="['mp4']" :file-size="4 * 100" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitVideoForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 新增比赛记录对话框 -->
    <el-dialog title="新增比赛记录" :visible.sync="recordDialogVisible" width="800px">
      <el-form :model="recordForm" :rules="recordRules" ref="recordForm" label-width="100px">
        <el-form-item label="记录时间" prop="time">
          <el-date-picker v-model="recordForm.time" type="datetime" placeholder="选择日期时间"
            value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%"> </el-date-picker>
        </el-form-item>
        <el-form-item label="进球球员" prop="name">
          <el-input v-model="recordForm.name" placeholder="请输入进球球员"></el-input>
        </el-form-item>
      </el-form>
      <div>
        <el-table :data="matchRecordList" border style="width: 100%">
          <el-table-column label="进球球员" prop="name" align="center" />
          <el-table-column label="进球时间" prop="time" align="center" />
          <!-- 删除 -->
          <el-table-column label="操作" align="center" width="100">
            <template slot-scope="scope">
              <el-button size="mini" type="danger" @click="handleDeletes(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="recordDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitRecordForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getMatchesList, createMatchesList, addMatchRecord, getMatchRecord, deleteMatchRecord, deleteMatchRecordById } from "@/api/lv/bs";
import FileUpload from "./../../components/FileUpload/index.vue";

export default {
  components: { FileUpload },
  data() {
    return {
      matchRecordList: [],
      matchesList: [],
      baseUrl: process.env.VUE_APP_BASE_API,
      loading: false,
      total: 0,
      query: {
        pageNum: 1,
        pageSize: 10
      },
      dialogVisible: false,
      currentRow: null,
      videoForm: {
        name: "",
        url: ""
      },
      rules: {
        name: [{ required: true, message: "请输入视频名称", trigger: "blur" }],
        url: [{ required: true, message: "请输入视频链接", trigger: "blur" }]
      },
      recordDialogVisible: false,
      recordForm: {
        matchId: null,
        time: "",
        name: ""
      },
      recordRules: {
        time: [{ required: true, message: "请选择记录时间", trigger: "change" }],
        name: [{ required: true, message: "请输入记录内容", trigger: "blur" }]
      }
    };
  },
  mounted() {
    this.getMatchesList();
  },
  methods: {
    handleDelete(row) {
      this.$confirm("确定删除该比赛吗?", "提示", {
        type: "warning"
      })
        .then(() => {
          // 删除逻辑
          deleteMatchRecord(row.id)
            .then(() => {
              this.$message.success("删除成功");
              this.getMatchesList();
            })
            .catch((error) => {
              console.error("删除比赛失败:", error);
              this.$message.error("删除失败");
            });

        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    handleDeletes(row) {
      this.$confirm("确定删除该比赛吗?", "提示", {
        type: "warning"
      })
        .then(() => {
          // 删除逻辑
          deleteMatchRecordById(row.id)
            .then(() => {
              this.$message.success("删除成功");
              this.recordDialogVisible = false;
            })
            .catch((error) => {
              console.error("删除比赛失败:", error);
              this.$message.error("删除失败");
            });

        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    async getMatchesList() {
      this.loading = true;
      try {
        const res = await getMatchesList(this.query);
        this.matchesList = res.data.records;
        this.total = res.data.total;
      } catch (error) {
        console.error("获取比赛列表失败:", error);
      } finally {
        this.loading = false;
      }
    },
    startEditing(row) {
      this.$set(row, "editing", true);
      row.originalRes = row.res;
    },
    cancelEdit(row) {
      row.editing = false;
      row.res = row.originalRes;
    },
    async handleScoreEdit(row) {
      try {
        await createMatchesList({
          id: row.id,
          res: row.res
        });
        this.$message.success("比分更新成功");
        row.editing = false;
      } catch (error) {
        this.$message.error("比分更新失败");
        console.error("更新比分失败:", error);
      }
    },
    parseVideos(videosStr) {
      try {
        const videos = JSON.parse(videosStr);
        return Array.isArray(videos) ? videos : [videos];
      } catch (e) {
        console.error("解析视频数据失败:", e);
        return [];
      }
    },
    handleExpand(row, expandedRows) {
      console.log("展开行:", row);
    },
    handleAddVideo(row) {
      this.currentRow = row;
      this.dialogVisible = true;
      this.videoForm = {
        name: "",
        url: ""
      };
    },
    submitVideoForm() {
      this.$refs.videoForm.validate((valid) => {
        if (valid) {
          try {
            const currentVideos = this.currentRow.videos ? JSON.parse(this.currentRow.videos) : [];
            const videos = Array.isArray(currentVideos) ? currentVideos : [currentVideos];
            videos.push(this.videoForm);

            const updateData = {
              ...this.currentRow,
              videos: JSON.stringify(videos)
            };

            createMatchesList(updateData).then(() => {
              this.$message.success("添加视频成功");
              this.getMatchesList();
              this.dialogVisible = false;
            });
          } catch (e) {
            console.error("处理视频数据失败:", e);
            this.$message.error("添加视频失败");
          }
        }
      });
    },
    handleAddjl(row) {
      this.recordDialogVisible = true;
      this.recordForm = {
        matchId: row.id,
        time: new Date().toISOString().slice(0, 19).replace("T", " "),
        name: ""
      };
      getMatchRecord(row.id).then((res) => {
        this.matchRecordList = res.data;
      });
    },
    submitRecordForm() {
      this.$refs.recordForm.validate(async (valid) => {
        if (valid) {
          try {
            await addMatchRecord(this.recordForm);
            this.$message.success("添加比赛记录成功");
            this.recordDialogVisible = false;
            this.getMatchesList();
          } catch (error) {
            console.error("添加比赛记录失败:", error);
            this.$message.error("添加比赛记录失败");
          }
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.team-info {
  display: flex;
  align-items: center;
  justify-content: center;

  .team-logo {
    width: 40px;
    height: 40px;
    margin-right: 8px;
    object-fit: cover;
  }
}

.el-table {
  .el-input {
    width: 100px;
  }

  span {
    cursor: pointer;

    &:hover {
      color: #409eff;
    }
  }

  .el-button+.el-button {
    margin-left: 5px;
  }
}

.videos-container {
  padding: 15px;
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.video-item {
  background: #f5f7fa;
  border-radius: 4px;
  padding: 8px;
  width: fit-content;
}

.video-name {
  font-size: 13px;
  color: #606266;
  margin-bottom: 6px;
  padding: 0 4px;
}

.video-player {
  width: 320px;
  height: 180px;
  border-radius: 4px;
  background: #000;
}
</style>
